<?php

namespace App\Console\Commands;

use App\Models\Article;
use Illuminate\Console\Command;
use QL\QueryList;

class FangArticle extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'spider:fang{page}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //获取命令行中的参数
        $page=$this->argument('page');
        //目标地址
        $url="https://news.ke.com/bj/baike/033/pg{$page}/";
        //获取请求得到目标地址的数据
        $html=http_request($url);
        //采集规则
        $rules=[
            'pic'=>['.item a img','data-original'],
            'title'=>['.item a img','alt'],
            'desn'=>['.item .summary','text'],
            'body'=>['.item a.img','href','',function($url){
                $html=http_request($url);
                $ret=QueryList::rules([
                   'body'=>['.bd','html']
                ])->html($html)->query()->getData();
                return $ret[0]['body'];
            }]
        ];
        $data=QueryList::rules($rules)->html($html)->query()->getData();
        //得到数据入库
        foreach ($data as $item){
            $item['cate_id']=2;
            $item['author']='佚名';
            Article::create($item);
        }
        echo "OK\n";
    }
}
